package com.andatsoft.laisim.entity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaMetadataRetriever;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.db.DataBaseAccess;
import com.andatsoft.laisim.theme.ThemeManager;
import com.andatsoft.laisim.utils.Utils;

public class Song {

	private int mId;
	private String mTitle;
	private String mAlbum;
	private String mArtist;
	private String mGenre;
	private int mBitRate;
	// private String mLyrics;
	private String mAddress;
	private int mDuration;
	private String mFolder;

	private boolean mHasAlbumArt;
	private boolean mIsFavorite;
	private int mPlayedTime;

	// audio effect id. 1 means no effect( the default profile)
	private int mEffectId = -1;

	public Song(Context c) {
		mTitle = c.getString(R.string.common_text_unknown_song_info);
		mAlbum = c.getString(R.string.common_text_unknown_song_info);
		mArtist = c.getString(R.string.common_text_unknown_song_info);
		mGenre = c.getString(R.string.common_text_unknown_song_info);
		mBitRate = 0;
		mIsFavorite = false;
		mPlayedTime = 0;
		mDuration = 0;
		mFolder = "";
	}

	public Song(Context c, String address) {
		this.mAddress = address;
		mIsFavorite = false;
		mPlayedTime = 0;
		this.mFolder = address.substring(0, mAddress.lastIndexOf("/"));
		updateSongInfo(c);
	}

	public Song(Context c, int mId, String mAddress, String mTitle,
			String mAlbum, String mArtist, String mGenre, int mBitRate,
			boolean mIsFavorite, int mPlayedTime, int dur, int effectId) {
		this.mId = mId;
		this.mTitle = mTitle;
		if (this.mTitle == null || this.mTitle.equals("")) {
			this.mTitle = mTitle = c
					.getString(R.string.common_text_unknown_song_info);
		}
		this.mAlbum = mAlbum;
		if (this.mAlbum == null || this.mAlbum.equals("")) {
			this.mAlbum = c.getString(R.string.common_text_unknown_song_info);
		}
		this.mArtist = mArtist;
		if (this.mArtist == null || this.mArtist.equals("")) {
			this.mArtist = c.getString(R.string.common_text_unknown_song_info);
		}
		this.mGenre = mGenre;
		if (this.mGenre == null || this.mGenre.equals("")) {
			this.mGenre = c.getString(R.string.common_text_unknown_song_info);
		}
		this.mBitRate = mBitRate;

		this.mAddress = mAddress;
		this.mIsFavorite = mIsFavorite;
		this.mPlayedTime = mPlayedTime;
		mDuration = dur;
		this.mFolder = mAddress.substring(0, mAddress.lastIndexOf("/"));
		this.mEffectId = effectId;
	}

	public int getId() {
		return mId;
	}

	public int getEffectId() {
		return mEffectId;
	}

	public void setEffectId(int id) {
		this.mEffectId = id;
	}

	public String getTitle() {
		return mTitle;
	}

	public void setTitle(String title) {
		this.mTitle = title;
	}

	public String getAlbum() {
		return mAlbum;
	}

	public void setAlbum(String album) {
		this.mAlbum = album;
	}

	public String getArtist() {
		return mArtist;
	}

	public void setArtist(String artist) {
		this.mArtist = artist;
	}

	public String getGenre() {
		return mGenre;
	}

	public void setGenre(String genre) {
		this.mGenre = genre;
	}

	public int getBitRate() {
		return mBitRate;
	}

	public String getBitRateString() {
		return mBitRate + " Kbps";
	}

	public void setBitRate(int bitRate) {
		this.mBitRate = bitRate;
	}

	public String getAddress() {
		return mAddress;
	}

	public void setaddress(String address) {
		this.mAddress = address;
	}

	public boolean isFavorite() {
		return mIsFavorite;
	}

	public void setFavorite(boolean isFavorite) {
		this.mIsFavorite = isFavorite;
	}

	public int getPlayedTime() {
		return mPlayedTime;
	}

	public void setPlayedTime(int mPlayedTime) {
		this.mPlayedTime = mPlayedTime;
	}

	public void updatePlayedTime() {
		mPlayedTime++;
	}

	public String getDurationString() {
		if (mDuration <= 0)
			return "--:--";
		return Utils.convertTimeToString(mDuration);
	}

	public int getDuration() {
		return mDuration;
	}

	public String getFolder() {
		return mFolder;
	}

	private boolean mIsExtracCalled;

	public Bitmap extractAlbumArt(Context c) {
		mIsExtracCalled = true;
		MediaMetadataRetriever retriever = new MediaMetadataRetriever();
		Bitmap bitmap = null;
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inSampleSize = 2;
		o.inPurgeable = true;
		o.inInputShareable = true;
		try {
			retriever.setDataSource(mAddress);
			byte[] pic = retriever.getEmbeddedPicture();
			if (pic == null) {
				// get from downloaded album art
				DataBaseAccess db = DataBaseAccess.getInstance(c);
				String path = db.getAlbumArtPath(mId);
				if (path != null) {
					mHasAlbumArt = true;
					bitmap = BitmapFactory.decodeFile(path);
					if (bitmap == null) {
						mHasAlbumArt = false;
						bitmap = ((BitmapDrawable) ThemeManager
								.getSelectedSkin().getDefaultAlbum())
								.getBitmap();
					}
				} else {
					mHasAlbumArt = false;
					if (ThemeManager.getSelectedSkin().getDefaultAlbum() == null
							|| (ThemeManager.getSelectedSkin()
									.getDefaultAlbum() != null && ((BitmapDrawable) ThemeManager
									.getSelectedSkin().getDefaultAlbum())
									.getBitmap().isRecycled())) {
						try {
							FileInputStream f = c.openFileInput("daa");
							bitmap = BitmapFactory.decodeStream(f);
							f.close();
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} else {
						bitmap = ((BitmapDrawable) ThemeManager
								.getSelectedSkin().getDefaultAlbum())
								.getBitmap();
					}
				}
			} else {
				mHasAlbumArt = true;
				bitmap = BitmapFactory.decodeByteArray(pic, 0, pic.length, o);
			}
		} catch (IllegalArgumentException iae) {
			iae.printStackTrace();
			mHasAlbumArt = false;
			return ((BitmapDrawable) ThemeManager.getSelectedSkin()
					.getDefaultAlbum()).getBitmap();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (retriever != null)
				retriever.release();
		}
		return bitmap;
	}

	public boolean hasAlbumArt() {
		if (mIsExtracCalled) {
			return mHasAlbumArt;
		}
		MediaMetadataRetriever retriever = new MediaMetadataRetriever();
		try {
			retriever.setDataSource(mAddress);
			byte[] pic = retriever.getEmbeddedPicture();
			if (pic == null) {
				mHasAlbumArt = false;
			} else {
				mHasAlbumArt = true;
			}
		} catch (IllegalArgumentException iae) {
			iae.printStackTrace();
			mHasAlbumArt = false;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (retriever != null)
				retriever.release();
		}
		return mHasAlbumArt;
	}

	private void calculateBitrate(int dur) {
		if (dur == 0)
			return;
		File f = new File(this.mAddress);
		long length = f.length();

		// 1000 ms = 1s
		long by = length * 1000 / dur;
		this.mBitRate = (int) (by * 8 / 1000);
	}

	public void updateSongInfo(Context c) {
		if (mAddress == null || mAddress.equals(""))
			return;
		MediaMetadataRetriever retriever = new MediaMetadataRetriever();
		try {
			retriever.setDataSource(mAddress);
			String metaData = retriever
					.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
			if (metaData == null) {
				this.mTitle = getSongTitleFromAddress();
			} else {
				this.mTitle = metaData;
			}
			metaData = retriever
					.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
			if (metaData != null) {
				this.mArtist = metaData;
			} else {
				this.mArtist = c
						.getString(R.string.common_text_unknown_song_info);
			}
			metaData = retriever
					.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
			if (metaData != null) {
				this.mAlbum = metaData;
			} else {
				this.mAlbum = c
						.getString(R.string.common_text_unknown_song_info);
			}
			metaData = retriever
					.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE);
			if (metaData != null) {
				this.mGenre = metaData;
			} else {
				this.mGenre = c
						.getString(R.string.common_text_unknown_song_info);
			}

			metaData = retriever
					.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
			if (metaData != null) {
				int str = Integer.parseInt(metaData);
				this.mDuration = str;
				calculateBitrate(str);
			} else {
				this.mDuration = 0;
			}
			// this.mBitRate =
			// retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE);
			// if (this.mBitRate == null) {
			// // calculate bitrate
			// }
		} catch (IllegalArgumentException iae) {
			iae.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (retriever != null)
				retriever.release();
		}

	}

	private String getSongTitleFromAddress() {
		String re = mAddress;
		int start = re.lastIndexOf('/');
		int end = re.lastIndexOf('.');
		return re.substring(start + 1, end);
	}

}
